<?php
 
use Phalcon\Mvc\Model\Criteria;
use Phalcon\Paginator\Adapter\Model as Paginator;

class UsersController extends ControllerBase
{

    public function indexAction()
    {
        $this->persistent->parameters = null;
        $numberPage = 1;
        if ($this->request->isPost()) {
            $query = Criteria::fromInput($this->di, "Users", $_POST);
            $this->persistent->parameters = $query->getParams();
        } else {
            $numberPage = $this->request->getQuery("page", "int");
        }

        $parameters = $this->persistent->parameters;
        if (!is_array($parameters)) {
            $parameters = array();
        }
        $parameters["order"] = "id";

        $users = Users::find($parameters);
        if (count($users) == 0) {
            $this->flash->notice("The search did not find any users");

            return $this->dispatcher->forward(array(
                "controller" => "users",
                "action" => "index"
            ));
        }

        $paginator = new Paginator(array(
            "data" => $users,
            "limit"=> 10,
            "page" => $numberPage
        ));

        $this->view->page = $paginator->getPaginate();
    }

    /**
     * Creates a new user
     */
    public function createAction()
    {

        if (!$this->request->isPost()) {
            return $this->dispatcher->forward(array(
                "controller" => "users",
                "action" => "index"
            ));
        }

        $user = new Users();

        $user->email = $this->request->getPost("email", "email");
        $user->name = $this->request->getPost("name");
        $user->password = $this->request->getPost("password");
        $user->role = $this->request->getPost("role");
        $user->blocked = $this->request->getPost("blocked");
        

        if (!$user->save()) {
            foreach ($user->getMessages() as $message) {
                $this->flash->error($message);
            }

            return $this->dispatcher->forward(array(
                "controller" => "users",
                "action" => "new"
            ));
        }

        $this->flash->success("user was created successfully");

        return $this->dispatcher->forward(array(
            "controller" => "users",
            "action" => "index"
        ));

    }
    

     public function signupAction() {
        $form = new SignUpForm();
        if ($this->request->isPost()) {
            if ($form->isValid($this->request->getPost())) {
                $user = new Users();

                $point = 0;
                $balance = 0;
                $balance_obj = \Models\References::findFirstById('balance');
                if ($balance_obj) {
                    $balance = $balance_obj->value;
                }
                $point_obj = \Models\References::findFirstById('point');
                if ($point_obj) {
                    $point = $point_obj->value;
                }

                $user->assign(array(
                    'username' => $this->request->getPost('username', 'striptags'),
                    'email' => $this->request->getPost('email'),
                    'password' => $this->security->hash($this->request->getPost('password')),
                    'fullName' => $this->request->getPost('name'),
                    'role_id' => 1,
                    'points' => $point,
                    'balance' => $balance,
                    'expired' => date('Y-m-d')
                ));
                if ($user->save()) {
                    return $this->response->redirect('login');
                } else {
                    foreach ($user->getMessages() as $value) {
                        $form->appendMessage($value, "signupsuccess", null);
                    }
                }
            }
        }
        $this->view->form = $form;
    }

    public function loginAction() {
        $identity = $this->auth->getIdentity();
        if ($identity) {
            return $this->response->redirect('profile');
        }
        $form = new LoginForm();
        if (!$this->request->isPost()) {

            if ($this->auth->hasRememberMe()) {
                $this->auth->loginWithRememberMe();
                return false;
            }
        } else {

            //valdate and print error in LoginForm function messages
            if ($form->isValid($this->request->getPost()) == true) {
                try {
                    $this->auth->check(array(
                        'username' => $this->request->getPost('username'),
                        'password' => $this->request->getPost('password'),
                        'remember' => $this->request->getPost('remember'),
                    ));

                    if ($this->request->getQuery('url') == true) {
                        //var_dump($this->request->getQuery('url'));
                        header('Location:' . $this->request->getQuery('url'));
                        return false;
                    }
                    header("Refresh:0");
                    /*                     * header('Location: index');
                      return false;* */
                } catch (\Library\Exception $e) {
                    $form->appendMessage($e->getMessage(), "loginfail", null);
                }
            }
        }
        $this->view->form = $form;
    }

    public function editAction(){
        
    }

    /**
     * Saves a user edited
     *
     */
    public function saveAction()
    {

        if (!$this->request->isPost()) {
            return $this->dispatcher->forward(array(
                "controller" => "users",
                "action" => "index"
            ));
        }

        $id = $this->request->getPost("id");

        $user = Users::findFirstByid($id);
        if (!$user) {
            $this->flash->error("user does not exist " . $id);

            return $this->dispatcher->forward(array(
                "controller" => "users",
                "action" => "index"
            ));
        }

        $user->email = $this->request->getPost("email", "email");
        $user->name = $this->request->getPost("name");
        $user->password = $this->request->getPost("password");
        $user->role = $this->request->getPost("role");
        $user->blocked = $this->request->getPost("blocked");
        

        if (!$user->save()) {

            foreach ($user->getMessages() as $message) {
                $this->flash->error($message);
            }

            return $this->dispatcher->forward(array(
                "controller" => "users",
                "action" => "edit",
                "params" => array($user->id)
            ));
        }

        $this->flash->success("user was updated successfully");

        return $this->dispatcher->forward(array(
            "controller" => "users",
            "action" => "index"
        ));

    }

    /**
     * Deletes a user
     *
     * @param string $id
     */
    public function deleteAction($id)
    {

        $user = Users::findFirstByid($id);
        if (!$user) {
            $this->flash->error("user was not found");

            return $this->dispatcher->forward(array(
                "controller" => "users",
                "action" => "index"
            ));
        }

        if (!$user->delete()) {

            foreach ($user->getMessages() as $message) {
                $this->flash->error($message);
            }

            return $this->dispatcher->forward(array(
                "controller" => "users",
                "action" => "search"
            ));
        }

        $this->flash->success("user was deleted successfully");

        return $this->dispatcher->forward(array(
            "controller" => "users",
            "action" => "index"
        ));
    }

}
